<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/7/25
 * Time: 16:36
 */

namespace app\admin\model;

use think\Config;
use think\exception\HttpResponseException;
use think\Response;

class ApiResponse
{
    public $code;
    public $msg;
    public $data;

    /**
     * @param null $data
     * @return ApiResponse
     */
    public static function success($data = null) : ApiResponse {
        $re = new static();
        $re->code = self::SUCCESS;
        $re->msg = 'success';
        $re->data = $data;
        return $re;
    }

    /**
     * @param int $code
     * @param null $msg
     * @return ApiResponse
     * @throws HttpResponseException
     */
    public static function error(int $code, $msg = null) : ApiResponse {
        $re = new static();
        $re->code = $code;
        $re->msg = $msg;

        $type = self::getResponseType();
        $response = Response::create($re, $type);
        throw new HttpResponseException($response);
    }

    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    protected static function getResponseType()
    {
        return Config::get('default_return_type');
    }

    
    // 错误码详见文档
    
    const SUCCESS = 200;

    const ERR_INVALID_REQUEST = 400;
    const ERR_INVALID_APP = 401;
    const ERR_INVALID_URI = 404;
    const ERR_SERVER = 500;
    const ERR_CHAT_SERVER = 600;
    const ERR_CHAT_LACK_AVATAR = 601;
    const ERR_FORM_INVALID = 1010;
    const ERR_TOKEN_INVALID = 1011;
    const ERR_OPERATE_FAILED = 1012;
    const ERR_PERMISSION_DENIED = 1021;

    const ERR_TEACHER_NULL = 2001;
    const ERR_EXISTS = 2002;

    const ERR_DATA_NULL = 3001;

    const EMPTY_PWD=4001;
    const ERROR_PWD=4002;
}